<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const arr = [
        {
          id: 1,
          name: '中华人民共和国',
          parentId: 0,
        },
        {
          id: 1001,
          name: '浙江省',
          parentId: 1,
        },
        {
          id: 2001,
          name: '杭州市',
          parentId: 1001,
        },
        {
          id: 3001,
          name: '西湖区',
          parentId: 2001,
        },
        {
          id: 4001,
          name: '杭州市第一人民医院',
          parentId: 3001,
        },
        {
          id: 1002,
          name: '河北省',
          parentId: 1,
        },
        {
          id: 2002,
          name: '石家庄',
          parentId: 1002,
        },
        {
          id: 3002,
          name: '赵县',
          parentId: 2002,
        },
        {
          id: 4002,
          name: '北王里',
          parentId: 3002,
        },
      ]

      // 非递归的方式  ---孩子找妈妈
      arr.forEach((item) => {
        arr.forEach((item1) => {
          if (item.parentId === item1.id) {
            if (item1.children) {
              item1.children = [item1.children, item]
            } else {
              item1.children = item
            }
          }
        })
      })
    </script>
  </body>
</html>
